package com.wyw.quartz.learning.common.job;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Objects;

/**
 * @Title
 * @Description
 * @Author Mr Wu yewen.wu.china@gmail.com
 * @Date 2024/3/29 17:53
 * Update History:
 * Author        Time            Content
 */
@DisallowConcurrentExecution
@Component
@Slf4j
public class DynamicJob implements Job {
    private static int count = 0;
    /**
     * 核心方法，Quartz Job真正的执行逻辑
     * @param executorContext   JonExceptionContext中封装有Quartz运行所需要的所有信息
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext executorContext) throws JobExecutionException {
        //JobDetail中的JobDataMap是公用的，从getMergedJobDataMap获取的JobDataMap是全新的对象
        JobDataMap map = executorContext.getMergedJobDataMap();
        String url = map.getString("url");
        String parameter = map.getString("parameter");//job参数
        Integer orderStatus = map.getIntValue("orderStatus");//订购状态，决定调用注册还是注销
        log.info("正在执行的Job name：{}， description：{}，group：{}，cron：%s，url：{}，parameter：{}，orderStatus：{}",
                map.getString("name"),  map.getString("jobDescription"), map.getString("jobGroup"),
                map.getString("cronExpression"), url, parameter, orderStatus);
        String requestURL = url + parameter;
        URI requestURI = URI.create(requestURL);


        long startTime = System.currentTimeMillis();
        //这里是定时任务执行的内容
        count++;

        long endTime = System.currentTimeMillis();
        log.info(">>>>>>>>>>>>> 正在执行的Job完成 count:{}, 耗时 : {}ms\n ",count, (endTime - startTime));

    }

    //记录Job执行内容
    private void logProcess(InputStream inputStream, InputStream errorStream) throws IOException {
        String inputLine;
        String errorLine;
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
        while(Objects.nonNull(inputLine = inputReader.readLine())) log.info("job 执行内容{}", inputLine);
        while(Objects.nonNull(errorLine = errorReader.readLine())) log.error("job 错误内容{}", errorLine);
    }

    //需要将方法提前准备好
//    @PostConstruct
//    private ResponseEntity<JSONObject> send(String requestURI){
//        return restTemplate.getForEntity(requestURI, JSONObject.class);
//    }
}

